package com.sky.controller.common;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import com.sky.service.common.CommonService;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 公共接口
 * @author zgp
 * @version V1.0
 * @date 2025-01-14 14:53
 */
@RestController
@RequestMapping
@Api(tags = "公共接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private CommonService commonService;

    @ApiOperation("文件上传")
    @PostMapping("/admin/common/upload")
    public Result<String> fileUpload(@RequestBody MultipartFile file){
        try {
            return Result.success(aliOssUtil.upload(file.getBytes(), file.getOriginalFilename()));
        } catch (IOException e) {
            log.error("文件上传错误：{}", e.getMessage(), e);
            throw new BaseException("文件上传失败:" + e.getMessage());
        }
    }

    @ApiOperation("骑手位置信息获取")
    @GetMapping("/dispatch/loadRouteInfo")
    public Result<String> loadRouteInfo(Long tradeNo, Integer courierId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime expire){
        log.info("骑手位置信息获取：tradeNo = {}, courierId = {}, expire = {}", tradeNo, courierId, expire);
        return Result.success(commonService.getRouteInfo(tradeNo, courierId, expire));
    }

    @ApiOperation("短链解析重定向")
    @GetMapping("/r/{code}")
    public void parseShortUrl(@PathVariable String code, HttpServletResponse response){
        String url = commonService.parseShortUrl(code);
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("短链重定向错误，{}", e.getMessage(), e);
        }
    }
}
